#include "Md5.c"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define ipad 0x36 // 00110110
#define opad 0x5c // 01011100

unsigned char Hash1[17];
unsigned char HMAC_value[17];


const int Blocksize = 64;
unsigned char *messgae = "admin"; //e320774659b1b23333bd033754d2ac1a
unsigned char *K = "admin";         //用来加密的密钥
unsigned char *Kp;                          // 使用密钥K生成的数据块
unsigned char *Si;
unsigned char *So;

//通过密钥k生成数据块
void generateKp()
{
    int i;
    Kp = (unsigned char *)malloc(sizeof(char)*Blocksize);
    for (i = 0; i < strlen(K); i++)
    {
        Kp[i] = K[i];
    }
    for (i = strlen(K); i < Blocksize; i++)
    {
        Kp[i] = 0;
    }

    Si = (unsigned char *)malloc(sizeof(char)*Blocksize);
    So = (unsigned char *)malloc(sizeof(char)*Blocksize);
    for (i = 0; i < Blocksize; i++)
    {
        Si[i] = Kp[i] ^ ipad;
        So[i] = Kp[i] ^ opad;
    }
}

//Hmac使用的实际Hash函数
void Hash(unsigned char *addS, unsigned long sLength, unsigned char *message, unsigned long mLength)
{
    int i;
    unsigned char * temp = (unsigned char *)malloc(sizeof(char) * (mLength+sLength+1));
    temp[mLength+sLength] = 0;
    // printf("Slength = %ld\nMlength = %ld\n",sLength,mLength);s
    for (i = 0; i < sLength; i++)
    {
        temp[i] = addS[i];
    }
    for (i = sLength;i < sLength + mLength; i++)
    {
        temp[i] = message[i-sLength];
    }
    MD5(temp,mLength+sLength);
    free(temp);
}

//释放所有的动态内存
void freeAllHmac()
{
    free(Kp);
    free(Si);
    free(So);
}

//真正的HMAC过程
void HMAC()
{
    printf("The message is %s\n",messgae);
    int i;
    generateKp();
    Hash1[16] = 0;
    HMAC_value[16] = 0;
    Hash(Si, Blocksize, messgae,strlen(messgae));
    for (i = 0; i < 16; i++)
    {
        Hash1[i] = hashRes[i];
    }
    // 输出中间的Hash值
    // for (int i = 0; i < 4 * 4; i++)
    // {
    //   printf("%02x ", hashRes[i]);
    // }
    // putchar('\n');
    
    Hash(So, Blocksize, Hash1, strlen(Hash1));

    for (i = 0; i < 16; i++)
    {
        HMAC_value[i] = hashRes[i];
    }
    printf("After HMAC, the result is \n");
    for (i = 0; i < 16; i++)
    {
        printf("%02x ", HMAC_value[i]);
    }
    printf("\n");
    freeAllHmac();
}

int main(){
    HMAC();
}




